﻿<%@ Page Language="C#" MasterPageFile="~/Shared/Masters/List.master" AutoEventWireup="true" Theme ="Default"
    CodeFile="OrgList.aspx.cs" Inherits="Modules_System_Org_List" Title="Untitled Page" %>

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
<%@ Register TagPrefix="web" TagName="listtitle" Src="~/Shared/UserControls/ListTitle.ascx" %>
<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>
<%@ Register Assembly="YYControls" Namespace="YYControls" TagPrefix="yyc" %>
<asp:Content ContentPlaceHolderID="idList" ID="idListContent" runat="server">
    <script type="text/javascript" src="../../Scripts/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="../../Scripts/jquery.checktree.0.3.min.js"></script>
    <script type="text/javascript" language="javascript">
        var m_dpmtRootNode = null;
        $(function(){
            var sl = document.createElement("link");
            sl.type = "text/css";
            sl.rel = "stylesheet";
            sl.href = "../../Scripts/css/checktree/checktree.css";
            document.getElementsByTagName("head")[0].appendChild(sl);
        
	        m_dpmtRootNode = $('#treeRoot');
		    showDpmtTree('#treeRoot', '#treeRoot', false, false);
        });
        
        function showDpmtTree(parentObj, rootTag, showCheck, withUpDown) {
	        var tmp = $(parentObj);
	        var needToLoad = false;
        	
	        if (parentObj == rootTag) {
		        if (tmp.find("li").length <= 1) {
			        needToLoad = true;
		        }
	        }
	        else {
		        if (!tmp.parent().attr("loaded")) {
			        needToLoad = true;
		        }
	        }
        	
	        if (needToLoad) {
		        getData(parentObj, function(json){
			        parseAllTree(json[0], parentObj, rootTag, showCheck, withUpDown);
		        });
	        }
        }
        
        function getData(parentDpmt, callback) {
	        var axel = Math.random() + "";
	        var num = axel * 1000000000000000000;
	        var pObj = $(parentDpmt);
	        var pid = "";
	        if (pObj) {
		        var lbl = pObj.parent().find("label");
		        if (lbl) {pid = lbl.attr("cid");}
	        }
        	
	        $.getJSON(
		        "OrgTreeAjax.aspx?ft=all",
		        {dc:num, ppid:pid, getTree:1},
		        function(json) {
			        callback(json);
		        }
	        );
        }
        
        function parseAllTree(data, target, rootTag, sc, wud) {
	        if (data && data.dpmt) {
		        var root = data.dpmt[0];
		        var startIndex = 0;
		        var rootElement = "";
        		
		        if (target != rootTag) {
			        if (data.dpmt.length > 0) {
				        var cid = $(target).parent().find("label").attr("cid");
				        root = {id:cid};
				        startIndex = 0;
			        }
			        else {
				        root = null;
			        }
		        }
		        else {
		            root = {id:0};
		        }
        		
		        rootElement += buildDepartmentTag(root, data.dpmt.slice(startIndex, data.dpmt.length), true);
        		
		        $(target).html(rootElement);
		        buildDpmtTree(target, rootTag, sc, wud);
	        }
        }
        
        function buildDpmtTree(target, rootNode, sc, wud) {
	        var tt = $(target);
	        var rn = m_dpmtRootNode;

	        tt.checkTree({
		        rootObj:rn,
		        index: target == 'treeRoot' ? 1 : 3,
		        showCheck: sc,
		        withUpDown: false,
		        onExpand:function(obj){
			        if (!obj.attr("loaded")) {
				        var tmp = obj.find("ul");
				        tmp.html("loading...");
				        if (tmp && tmp.length > 0){
					        showDpmtTree(tmp[0], rn, sc, wud);
				        }
			        }
			        obj.attr("loaded","true");
		        },
		        onSelection:function(obj) {
		            cancelEdit(obj);
		        }
	        });
        	
	        if (target == rootNode) {
		        var r = tt.find('.arrow');
		        if (r.length > 0) {
			        var tmp = $(r[0]);
			        tmp.parent().attr("loaded","true");
			        tmp.trigger('click');
		        }
	        }
        }
        
        function buildDepartmentTag(p, t, isAddChild) {
	        var h = "";
	        for(var i = 0; i < t.length; i++) {
		        var tmp = t[i];
		        if (tmp.parentId == p.id || tmp.parentId == 0) {
			        h += "<li class='parent'><input type='checkbox' class='cb' /><img src='../../Scripts/css/checktree/images/02.jpg' style='width:22px;height:16px;padding:0'/><label type='dpmt' cid='" + tmp.id + "' pid='" + tmp.parentId + "' orgType='" + tmp.type + "' status='" + tmp.status + "' code='" + tmp.code + "'>" + tmp.name + "</label>";
        			
			        var child = buildDepartmentTag(tmp, t.slice(i + 1, t.length), true);
			        var mbt = "";
			        if (child != "" || mbt != null) {
				        h = h + "<ul>" + child + mbt + "</ul>";
			        }
			        h += "</li>";
		        }
	        }
        	
	        return h;
        }
        
        function getSelectedDpmtNode() {
	        var lbs = $('#treeRoot').find('label');
	        if (lbs.length > 0) {
		        for(var i = 0; i < lbs.length; i++) {
			        var lbl = lbs[i];
			        if (lbl.getAttribute("selected") == "true") {
				        return lbl;
			        }
		        }
	        }
	        return null;
        }
        
        function editOrg(isNew) {
            if(isNew) {
                var parent = getSelectedDpmtNode();
                if(!parent){
                    $("#txtParentId").val("");
                    alert("请选择上级部门");
                    return false;
                } else if(parent.getAttribute("orgtype") == "0") {
                    alert("普通部门不能再添加下级部门");
                    return false;
                }else{
                    $("#txtParentId").val($(parent).attr("cid"));
                }
                $("#txtId").val("");
                $("#txtCode").val("").attr("disabled","");
                $("#txtName").val("").attr("disabled","");
                $("#ddlStatus").val(1).attr("disabled","");
                $("#ddlType").val(0).attr("disabled","");
                $("#btnSave").css("visibility","visible");
                $("#btnReset").css("visibility","visible");
            }
            else {
                var selected = getSelectedDpmtNode();
                if(selected == null) {
                    alert("请选择要修改的部门！");
                    return;
                }
                selected = $(selected);
                $("#txtParentId").val(selected.attr("pid"));
                $("#txtId").val(selected.attr("cid"));
                $("#txtCode").val(selected.attr("code")).attr("disabled","");
                $("#txtName").val(selected.html()).attr("disabled","");
                $("#ddlStatus").val(selected.attr("status")).attr("disabled","");
                $("#ddlType").val(selected.attr("orgtype")).attr("disabled","");
                $("#btnSave").css("visibility","visible");
                $("#btnReset").css("visibility","visible");
            }
        }
        
        function cancelEdit(obj) {
            var selected = obj ? obj : getSelectedDpmtNode();
            var lbs = selected ? (obj ? $(selected).find('label') : $(selected)) : null;
            $("#txtParentId").val(lbs ? lbs.attr("pid") : "");
            $("#txtId").val(lbs ? lbs.attr("cid") : "");
            $("#txtCode").val(lbs ? lbs.attr("code") : "").attr("disabled","disabled");
            $("#txtName").val(lbs ? lbs.html() : "").attr("disabled","disabled");
            $("#ddlStatus").val(lbs ? lbs.attr("status") : 1).attr("disabled","disabled");
            $("#ddlType").val(lbs ? lbs.attr("orgtype") : 0).attr("disabled","disabled");
            $("#btnSave").css("visibility","hidden");
            $("#btnReset").css("visibility","hidden");
        }
        
        function doSave() {
            var id = $("#txtId").val();
            var parentId = $("#txtParentId").val();
            var code = $("#txtCode").val();
            var name = $("#txtName").val();
            var status = $("#ddlStatus").val();
            var type = $("#ddlType").val();
            
            if(code == null || $.trim(code) == "") {
                alert("代码必填！");
                return false;
            }
            if(name == null || $.trim(name) == "") {
                alert("名称必填！");
                return false;
            }
            
            $.ajax({type:"post",
                url:"OrgTreeAjax.aspx?method=save", 
                data:{id:id, pid:parentId, code:code, name:name, status:status, type:type}, 
                success : function(result){
                    try {
                        var json = eval(result);
                        if(json[0].resultCode != 0) {
                            alert(json[0].errMsg);
                            return false;
                        }
                        else {
                            if(id) {
                                var current = getSelectedDpmtNode();
                                current.setAttribute("orgtype", type);
                                current.setAttribute("status", status);
                                current.setAttribute("code", code);
                                $(current).html(name);
                            }
                            else {
                                id = json[0].id;
                                
                                var h = "<li class='parent'><input type='checkbox' class='cb' /><img src='../../Scripts/css/checktree/images/02.jpg' style='width:22px;height:16px;padding:0'/><label type='dpmt' cid='" + id + "' pid='" + parentId + "' orgType='" + type + "' status='" + status + "' code='" + code + "'>" + name + "</label>";
			                    h += "</li>";
			                    var parent = getSelectedDpmtNode();
			                    var childContainer = $(parent.parentNode).find("ul");
			                    if(!childContainer || childContainer.length == 0) {
			                        //h = "<ul>" + h + "</ul>";
			                        childContainer = $("<ul style='display:none'></ul>");
			                        $(parent.parentNode).append(childContainer);
			                    }
			                    childContainer.append($(h));
			                    buildDpmtTree(childContainer, "#treeRoot", false, false);
			                }
			                
			                cancelEdit(null);
                        }
                    }
                    catch(e){
                        window.location = "../../Login.aspx";
                    }
                },
                error : function(err) {
                    alert(err);
                }
            });
        }
        
        function deleteOrg() {
            var current = getSelectedDpmtNode();
            if(current == null) {
                alert("请选择要删除的部门！");
                return false;
            }
            
            var child = $(current.parentNode).find("ul");
            if(child && child.length > 0 && child[0].childNodes && child[0].childNodes.length > 0) {
                alert("该部门还有下级部门，不能删除");
                return false;
            }
            if(current.getAttribute("orgtype") == "1") {
                alert("顶级部门不能删除！");
                return false;
            }
            
            var id = current.getAttribute("cid");
            if(window.confirm("确实要删除该部门？")) {
                $.ajax({type:"post",
                    url:"OrgTreeAjax.aspx?method=del", 
                    data:{id:id}, 
                    success : function(result){
                        try {
                            var json = eval(result);
                            if(json[0].resultCode != 0) {
                                alert(json[0].errMsg);
                                return false;
                            }
                            else {
                                var parent = $(current.parentNode);
                                parent.remove();
                            }
                        }
                        catch(e){
                            window.location = "../../Login.aspx";
                        }
                    },
                    error : function(err) {
                        alert(err);
                    }
                });
            }
        }
    </script>
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div class="crumb">
        <asp:Label runat="server" ID="lblTitle" Text="部门管理"></asp:Label>
    </div>
    <div style="height:400px;width:300px;border:1px solid; margin:10px;float:left;" id="searchtree">
		<ul id="treeRoot" class="tree1 tree" style="margin-left: 5px;OVERFLOW:auto; height:350px;">
			<li>
				<label>loading...</label>
			</li>
		</ul>
	</div>
	<div style="margin:10px;border:0px;width:250px;text-align:center;float:left;">
        <table cellpadding='2' cellspacing='1' class='ow_fim_mg' width='100%'>
            <tr>
                <td colspan="2">
                    <asp:LinkButton ID="lbtnNew" runat="server" Text="新增"  OnClientClick="editOrg(true);return false;"></asp:LinkButton>&nbsp;
                    <asp:LinkButton ID="lbtnMod" runat="server" Text="修改" OnClientClick="editOrg(false);return false;"></asp:LinkButton>&nbsp;
                    <asp:LinkButton ID="lbtnDel" runat="server" Text="删除" OnClientClick="deleteOrg(); return false;"></asp:LinkButton>
               </td>
            </tr>
            <tr><td colspan="2">&nbsp;</td></tr>
            <tr>
                <td class='fi_l'>
                    <input type="hidden" id="txtParentId" name="ParentID" value="" />
                    <input type="hidden" id="txtId" name="ID" value="" />
                    <asp:Label ID="lbCode" runat="server" Text="代码:"></asp:Label><font color='red'>*</font>
                </td>
                <td class='fi_r'>
                    <input type="text" id="txtCode" name="Code" style="width:120px;" disabled="disabled" maxlength="50" />
                    </td>
            </tr>   
            <tr>
                <td class='fi_l'>
                    <asp:Label ID="lbName" runat="server" Text="名称:"></asp:Label><font color='red'>*</font>
                </td>
                <td class='fi_r'>
                    <input type="text" name="Name" id="txtName" style="width:120px" disabled="disabled" maxlength='50'></input>
                </td>
            </tr>
            <tr>
                <td class='fi_l'>
                    <asp:Label ID="lbType" runat="server" Text="类型:"></asp:Label><font color='red'>*</font>
                </td>
                <td class='fi_r'>
                    <select id="ddlType" name="Type" style="width:120px" disabled="disabled">
                        <option selected="selected" value="0">普通部门</option>
                        <option value="2">机关</option>
                        <option value="3">工商所</option>
                        <option value="1">分局</option>
                    </select>
                </td>
            </tr>
            <tr>
                <td class='fi_l'>
                    <asp:Label ID="lbStatus" runat="server" Text="状态:"></asp:Label><font color='red'>*</font>
                </td>
                <td class='fi_r'>
                    <select id="ddlStatus" name="Status" style="width:120px" disabled="disabled">
                        <option selected="selected" value="1">有效</option>
                        <option value="0">无效</option>
                    </select>
                </td>
            </tr>
            <tr><td colspan="2">&nbsp;</td></tr>
            <tr>
                <td colspan="2" style="text-align:center">
                    <input type="button" id="btnSave" value="保存" style="visibility:hidden" onclick="doSave();" />&nbsp;&nbsp;
                    <input type="button" onclick="cancelEdit(null);" id="btnReset" value="取消" style="visibility:hidden" />
                </td>
            </tr>
        </table>
	</div>
</asp:Content>
